﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace DotnetSpider.Lawyee.Src
{
	public class EncryptHelper
	{


		//3DES的cbc加密[24位密钥对应192位加密]
		public static string TripleDesEncryptorCBC(string text, string key, string iv)
		{
			var tripleDESCipher = new TripleDESCryptoServiceProvider();
			tripleDESCipher.Mode = CipherMode.CBC;
			tripleDESCipher.Padding = PaddingMode.PKCS7;
			byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);
			byte[] keyBytes = new byte[24];
			int len = pwdBytes.Length;
			if (len > keyBytes.Length)
				len = keyBytes.Length;
			System.Array.Copy(pwdBytes, keyBytes, len);
			tripleDESCipher.Key = keyBytes;
			tripleDESCipher.IV = Encoding.ASCII.GetBytes(iv);

			ICryptoTransform transform = tripleDESCipher.CreateEncryptor();
			byte[] plainText = Encoding.UTF8.GetBytes(text);
			byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
			return Convert.ToBase64String(cipherBytes);
		}

		//3DES的cbc解密
		public static string TripleDesDecryptorCBC(string text, string key, string iv)
		{
			var tripleDESCipher = new TripleDESCryptoServiceProvider();
			tripleDESCipher.Mode = CipherMode.CBC;
			tripleDESCipher.Padding = PaddingMode.PKCS7;

			byte[] encryptedData = Convert.FromBase64String(text);
			byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);
			byte[] keyBytes = new byte[24];
			byte[] ivBytes = Encoding.ASCII.GetBytes(iv);
			int len = pwdBytes.Length;
			if (len > keyBytes.Length)
				len = keyBytes.Length;
			System.Array.Copy(pwdBytes, keyBytes, len);
			tripleDESCipher.Key = keyBytes;
			tripleDESCipher.IV = ivBytes;
			ICryptoTransform transform = tripleDESCipher.CreateDecryptor();
			byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
			return Encoding.UTF8.GetString(plainText);
		}


	}
}
